<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->

<template>
  <div class="min-h-screen bg-gray-50">

    <div class="container mx-auto max-w-5xl p-6">
      <!-- 基本信息 -->
      <div class="profile-section bg-white rounded-lg shadow-md mb-8 overflow-hidden">
        <div class="section-body">
          <div class="max-w-7xl mx-auto px-5">
            <!-- 顶部导航标签 -->
            <div class="following-tabs flex border-b border-gray-200 mb-6 overflow-x-auto">
              <button v-for="(tab, index) in tabs" :key="index" :class="[
                'tab-btn py-3 px-6 text-sm font-medium whitespace-nowrap relative transition-colors',
                queryParams.status === tab.value ? 'text-blue-500' : 'text-gray-500 hover:text-gray-700'
              ]" @click="tabChange(tab.value)">
                {{ tab.label }}
                <span v-if="queryParams.status === tab.value"
                  class="absolute bottom-0 left-0 w-full h-0.5 bg-blue-500"></span>
              </button>

              <el-select style="width: 120px;" v-model="sort.order" class="w-32 ml-auto" @change="sortChange">
                <el-option label="时间升序" value="ASC" />
                <el-option label="时间降序" value="DESC" />
              </el-select>
            </div>

            <!-- 活动列表 -->
            <div class="space-y-6">
              <div v-for="(event, index) in events" :key="index" class="bg-white rounded-lg shadow-sm overflow-hidden">
                <div class="p-6">
                  <div class="flex space-x-6">
                    <!-- 活动海报 -->
                    <div class="w-72 h-40 rounded-lg overflow-hidden">
                      <img :src="event.posterUrl" @click="goActivityDetail(event.id)" class="w-full h-full object-cover"
                        :alt="event.title">
                    </div>

                    <!-- 活动信息 -->
                    <div class="flex-1">
                      <h3 class="text-xl font-medium mb-4">{{ event.activityTitle }}</h3>
                      <div class="space-y-3 text-gray-600">
                        <div class="flex items-center space-x-2">
                          <el-icon>
                            <Calendar />
                          </el-icon>
                          <span>{{ event.startTime }}-{{ event.endTime }}</span>
                        </div>
                        <div class="flex items-center space-x-2">
                          <el-icon>
                            <Location />
                          </el-icon>
                          <span>{{ event.address }}</span>
                        </div>
                        <div class="flex items-center space-x-2">
                          <span class="text-2xl font-medium text-gray-900">票价: {{ event.price }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- 票务信息表格 -->
                  <el-table :data="event.tickets" style="width: 100%" class="mt-6">
                    <el-table-column prop="type" align="center" label="票种" width="180">
                      <template #default="scope">
                        {{activity_ticket_type.filter(item => item.dictValue == scope.row.type)[0]?.dictLabel}}
                      </template>
                    </el-table-column>
                    <el-table-column prop="price" align="center" label="价格" width="180" />
                    <el-table-column prop="paid" align="center" label="实付" width="180" />
                    <el-table-column prop="status" align="center" label="状态" width="180">
                      <template #default="scope">
                        {{ scope.row.status === 'PENDING' ? "待参加" : '' }}
                        {{ scope.row.status === 'AUDITING' ? "待审核" : '' }}
                        {{ scope.row.status === 'UNPAID' ? "待付款" : '' }}
                        {{ scope.row.status === 'REFUNDED' ? "退票" : '' }}
                        {{ scope.row.status === 'APPROVED' ? "审核通过" : '' }}
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                      <template #default="scope">
                        <template v-if="scope.row.status !== 'REFUNDED'">
                          <div class="space-x-4" v-if="event.canCancel">
                            <el-button type="warning" @click="cancelBoxShow(event)">
                              取消报名
                            </el-button>
                            <el-popover placement="left" :width="600" trigger="click">
                              <template #reference>
                                <el-button type="primary">
                                  电子票
                                </el-button>
                              </template>
                              <ticket-box :id="event.id"></ticket-box>
                            </el-popover>
                          </div>
                          <div v-else>
                            <el-tag type="info">
                              活动已结束
                            </el-tag>
                          </div>
                        </template>
                        <template v-else>
                          <el-tag type="info">
                            已退票
                          </el-tag>
                          <el-tag type="success" style="margin-left: 10px;" @click="goActivityDetail(event.id)">
                            重新报名
                          </el-tag>
                        </template>

                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
            <!-- 空状态 -->
            <div v-if="events.length === 0" class="empty-state text-center">
              <div class="empty-icon text-5xl text-gray-300 mb-4">
                <i class="fas fa-bookmark"></i>
              </div>
              <div class="empty-text text-xl font-medium text-gray-700 mb-2">暂无活动</div>
              <div class="empty-subtext text-gray-500 mb-6">您可以报名参加活动，以便日后查阅</div>

            </div>

            <!-- 分页 -->
            <div class="flex justify-center items-center mt-8">
              <el-pagination background layout="prev, pager, next" v-show="queryParams.total > 0"
                @current-change="getMyActivitiesFun" :page-size="queryParams.pageSize" :total="queryParams.total" />
            </div>


          </div>

        </div>
      </div>
    </div>



  </div>
  <client-only>
    <el-dialog v-model="centerDialogVisible" title="提示" width="500" center>
      <span>
        是否确认取消报名?
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="getActivityCancelFun">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </client-only>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { getMyActivities } from "@/api/user";
import { getActivityCancel } from "@/api/activity";
import { Calendar, Location, Timer, ArrowDown, ArrowUp } from '@element-plus/icons-vue';
import dayjs from 'dayjs'
import { getDictTypes } from "@/api/dict";
const tabs = [
  { label: '全部', value: 'ALL' },
  { label: '待参加', value: 'PENDING' },
  { label: '待审核', value: 'AUDITING' },
  { label: '待付款', value: 'UNPAID' },
  { label: '退票', value: 'REFUNDED' }
];
import { useRoute } from "vue-router";
// 取消报名
const centerDialogVisible = ref(false)



const router = useRouter()

const goActivityDetail = (id) => {
  const targetRoute = router.resolve({ path: '/activity/activePage', query: { id: id } });
  window.open(targetRoute.href, '_blank');
}

const activityItem = ref(null)

// 取消报名弹窗
const cancelBoxShow = (event) => {
  const endTimeMs = dayjs(event.endTime * 1000).valueOf();
  const nowMs = dayjs().valueOf();
  const distance = endTimeMs - nowMs;
  if (distance < 0) {
    getMyActivitiesFun();
    ElNotification({
      title: '活动已结束',
      type: 'Warning',
    })
  } else {
    centerDialogVisible.value = true;
    activityItem.value = event;
  }
}

// 取消报名
const getActivityCancelFun = (id) => {
  getActivityCancel({ reason: '', activityId: activityItem.value.id }).then((res) => {
    if (res.suc) {
      ElNotification({
        title: '取消报名成功',
        type: 'success',
      })
    }
  }).finally(() => {
    getMyActivitiesFun();
    centerDialogVisible.value = false
  })
}


// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 12,
  "sorts": [],
  status: 'ALL'
})

const sort = ref({
  condition: 'created_at',
  order: 'ASC'// ASC-升序, DESC-降序
})

const tabChange = (val) => {
  queryParams.value.status = val
  getMyActivitiesFun()
}

const sortChange = (order) => {
  sort.value.order = order
  getMyActivitiesFun()
}

const getMyActivitiesFun = () => {
  queryParams.value.sorts = [sort.value];
  getMyActivities(queryParams.value).then(res => {
    queryParams.value.total = res.data.total;
    res.data.list.forEach((item) => {
      const startTimeMs = dayjs(item.endTime).valueOf();
      console.log(startTimeMs)
      const nowMs = dayjs().valueOf();
      const distance = startTimeMs - nowMs;

      if (distance < 0) {
        item.canCancel = false;
      } else {
        item.canCancel = true;
      }

      item.tickets = [{
        type: item.ticketType,
        price: item.price,
        paid: item.actualPaid,
        status: item.status,
        tool: '',
      }]
    })
    events.value = res.data.list;
  })
}

const activity_ticket_type = ref([])

const getDictTypesFun = async () => {
  getDictTypes({ types: 'activity_ticket_type' }).then(res => {
    activity_ticket_type.value = res.data.activity_ticket_type;
    console.log(activity_ticket_type.value)
  })
}

onMounted(() => {
  getMyActivitiesFun();
  getDictTypesFun();
})

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

const events = ref([]);

const handleAction = (row) => {

};
</script>

<style scoped>
.el-table :deep(.el-table__header) {
  background-color: #f8f9fa;
}

.el-table :deep(.el-table__row) {
  cursor: pointer;
}

.el-table :deep(.el-button) {
  padding: 8px 16px;
}
</style>
